<template>
  <div>
    <!-- 顶部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品编辑</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- card -->
    <el-card class="box-card">
      <!-- 消息提醒框 -->
      <el-alert title="编辑商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- step 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 最外层有个大的表单嵌套 -->
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-position="top">
        <!-- tabs -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          :before-leave="beforeLeave"
          @tab-click="handleTabClick1"
        >
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="editForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="editForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="editForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="editForm.goods_number" type="number"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form-item v-for="item in manyList" :key="item.attr_id" :label="item.attr_name">
              <!-- 渲染的多选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(val,index) in item.attr_vals" :label="val" :key="index" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item v-for="item in onlyList" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- <el-tab-pane label="商品图片">
            <el-upload
              multiple
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleUploadSuccess"
              :headers="headerObj"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>-->
          <el-tab-pane label="商品内容">
            <quill-editor v-model="editForm.goods_introduce"></quill-editor>
            <br />
            <el-button type="primary" @click="editSubmit">编辑商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览大图的弹框 -->
      <el-dialog title="图片预览" :visible.sync="dialogVisible" width="50%">
        <img :src="this.previewPath" alt="图片" width="100%" />
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import { reqAllCateList, reqEditGood, reqUpload, reqGoodId } from '../../api/index'
export default {
  name: 'editGood',
  data () {
    return {
      // step 和 tabs 切换的联动索引值
      activeIndex: '0',

      // 编辑表单需要的数据
      editForm: {},
      // 编辑表单的校验规则
      editRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
      },
      // 动态参数列表
      manyList: [],
      // 静态参数列表
      onlyList: [],

      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },

      // 图片的大图预览
      dialogVisible: false,
      // 预览的图片路径
      previewPath: '',

      content: '',

    }
  },
  methods: {
    async getEditForm () {
      const res = await reqGoodId(this.$route.params.id)

      this.editForm = res.data
      this.editForm.attrs.map(params => {
        if (params.attr_sel === 'only') {
          this.onlyList.push(params)
        } else if (params.attr_sel === 'many') {
          params.attr_vals = params.attr_vals ? params.attr_vals.split(',') : []
          this.manyList.push(params)
        }
      })
      console.log(this.editForm)
    },
    // 将要离开面板的钩子函数
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.editForm.goods_name === '') {
        this.$message.error('请填写相关参数')
        return false
      }
    },

    // 图片移除
    handleRemove (file) {
      // 1. 找到需要删除图片的临时路径
      const img = file.response.data.tmp_path
      // 2. 从pics数组中找到该临时路径的索引值
      const index = this.editForm.pics.findIndex(item => item.pic === img)
      // 3. 从数组中移除
      this.editForm.pics.splice(index, 1)
      console.log(this.editForm)
    },

    // 图片预览
    handlePreview (file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.dialogVisible = true
    },

    // 上传成功
    handleUploadSuccess (response) {
      console.log(response)
      // 1. 拼接一个对象给后台的上传
      const imgInfo = { "pic": response.data.tmp_path }
      // 2. 将图片文件保存到表单中
      this.editForm.pics.push(imgInfo)
      console.log(this.editForm)
    },

    // 编辑商品的校验
    editSubmit () {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('请填写相关参数')
        } else {
          // 将动态参数和静态参数转成数组
          this.manyList.forEach((item) => {
            const info = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
            this.editForm.attrs.push(info)
          })

          this.onlyList.forEach(item => {
            const info = { attr_id: item.attr_id, attr_value: item.attr_vals }
            this.editForm.attrs.push(info)
          })

          const result = await reqEditGood(Number(this.$route.params.id), this.editForm)
          if (result.meta.status === 200) {
            this.$message.success('编辑商品成功')
            this.$router.replace('/goods')

          } else {
            this.$message.error(result.meta.msg)
          }
        }
      })
    }


  },
  created () {
    this.getEditForm()
  },
}
</script>
<style lang="less" scoped>
.el-card {
  margin-top: 15px;

  .el-tabs {
    margin-top: 30px;
  }

  .el-cascader {
    width: 100%;
  }
  .el-checkbox {
    margin: 0 10px 10px 0 !important;
  }
}
</style>
